Skip to main content

微信支付 之 支付成功验证微信支付签名

微信支付成功后 会调用商家的notify_url,能否正确验证是个小难点

下面是我在ecshop里面整合的部分代码

efine('IN_ECS', true);

logResult(json_encode($_REQUEST));
logResult(json_encode($_GET));
logResult(json_encode($_POST));

$xml = file_get_contents('php://input');
logResult($xml);

logResult(json_encode($_SERVER));

function logResult($word=") {
$fp = fopen('wxpay_log.txt',"a");
flock($fp, LOCK_EX) ;
fwrite($fp,"执行日期:".strftime("%Y%m%d%H%M%S",time())."\n".$word."\n");
flock($fp, LOCK_UN);
fclose($fp);
}

logResult('|_1_|');

if(empty($_REQUEST['bank_type']) || empty($_REQUEST))
{
die('fail');
}

logResult('|_2_|');

//如果为空就是正确的
if(empty($_REQUEST['pay_info']) && !empty($_REQUEST['sign']) && !empty($_REQUEST['out_trade_no']))
{
logResult('|_3_|');

@define(APPID , ""); //appid
@define(APPKEY ,""); //paysign key
@define(SIGNTYPE, "sha1″); //method
@define(PARTNERID,"");//通加密串
@define(PARTNERKEY,"");//通加密串
@define(APPSERCERT, "");

$out_trade_no = $_REQUEST['out_trade_no'];

include_once('init.php');
include_once(ROOT_PATH . 'includes/lib_payment.php');

$order_sn = substr($out_trade_no,0,13);
$log_id = substr($out_trade_no,13);
logResult('|_4_|'.$log_id.'||');

//确认接收数据成功,调用接口通知微信成功
logResult('|_5_|'.$log_id);
$wxPayHelper = new WxPayHelper();

//验证签名是否正确
$is_sign = $wxPayHelper->verifySign($_REQUEST);
if($is_sign && $_REQUEST['trade_state'] == 0 )
{
$str_ddd = 'ok||'.$is_sign.'||';
logResult('|_6_|'.$str_ddd);
//修改订单状态
order_paid( $log_id, 2);

//存入发货通知需要的数据
$xml = new SimpleXMLElement($xml);

$WxData['openId'] == (string)$xml->OpenId ;
$WxData['transaction_id'] == $_REQUEST['transaction_id'];
$WxData['out_trade_no'] == $out_trade_no;

echo 'success';
}else
{
echo 'fail';
}
}else
{
logResult('|_7_|'.'fail');
echo 'fail';
}

下面是加在官方demo WxPayHelper类里面的方法。

//验证微信支付签名
public function verifySign($sign_arr)
{
$commonUtil = new CommonUtil();
$MD5SignUtil = new MD5SignUtil();

foreach($sign_arr as $key => $value )
{
if($key != 'sign' && $value != " && $value != NULL && $value != 'null' )
{
$new_sign_arr[$key] = $value;
}
}
// 对签名字段按ascii码从小到大排序组成字符串
$content = $commonUtil -> formatBizQueryParaMap($new_sign_arr,false);

return $MD5SignUtil->verifySignature($content,$sign_arr['sign'],PARTNERKEY);
}